<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="70px"
    >
      <el-form-item label="访问人" prop="accessUserName">
        <el-input
          v-model="queryParams.accessUserName"
          placeholder="请输入访问人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="审核状态"
          clearable
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table v-loading="loading" border :data="tableList">
      <el-table-column label="访问人" align="center" prop="accessUserName" />
      <el-table-column label="访问码" align="center" prop="accessCode" />
      <el-table-column label="访问时长" align="center" prop="accessInterval">
        <template slot-scope="scope">
          <span v-if="scope.row.intervalType == 1">{{
            getValue(accessIntervalOptions, scope.row.accessInterval)
          }}</span>
          <span v-else>{{ scope.row.accessInterval / 60 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="审核状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ getValue(statusOptions, scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="submitUserName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleApprove(scope.row)"
            v-if="isAdmin && scope.row.status == 0"
            >审核</el-button
          >
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getTableList"
    />

    <!-- 新增/修改 -->
    <el-dialog :title="title" :visible.sync="open" width="800" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24" style="display: flex; flex-wrap: wrap;">
          <el-col :span="12">
            <el-form-item label="访问人" prop="accessUserName">
              <el-input
                v-model="form.accessUserName"
                placeholder="请输入访问人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问码" prop="accessCode">
              <div class="input-group">
                <el-input
                  v-model="form.accessCode"
                  placeholder="请生成访问码"
                  @change="handleCodeChange"
                />
                <span @click="generateCode()">随机生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义时长" prop="intervalType">
              <el-radio-group
                v-model="form.intervalType"
                @input="intervalTypeChange()"
              >
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问时长" prop="accessInterval">
              <div class="input-group">
                <el-select
                  v-model="form.accessInterval"
                  placeholder="请选择访问时长"
                  v-if="form.intervalType == 1"
                >
                  <el-option
                    v-for="item in accessIntervalOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                <el-input
                  v-model="form.accessInterval"
                  placeholder="请输入访问时长"
                  @input="handleAccessIntervalInput"
                  v-else
                />
                <span>分钟</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问次数" prop="accessCount">
              <el-input
                v-model="form.accessCount"
                placeholder="请输入访问次数"
                @input="handleAccessCountInput"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效时间" prop="validTime">
              <el-date-picker
                v-model="form.validTime"
                type="datetimerange"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 100%"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人" prop="submitUserId">
              <el-select
                v-model="form.submitUserId"
                filterable
                remote
                :remote-method="remoteMethod"
                placeholder="请选择申请人"
                style="width: 100%"
                @change="handleChange"
                @focus="handleFocus"
                v-if="isAdmin"
              >
                <el-option
                  v-for="item in submitUserIdOptions"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                ></el-option>
                <div v-if="hasMore" class="load-more" @click="loadMore">
                  加载更多
                </div>
              </el-select>
              <el-input v-model="form.submitUserName" disabled v-else />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问场景" prop="deviceId">
              <el-cascader
                v-model="form.deviceId"
                :options="cameraTreeList"
                :props="{ multiple: true, value: 'id', label: 'name' }"
                collapse-tags
                clearable
                style="width: 100%"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog
      title="访问码审核"
      :visible.sync="statusOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="statusForm"
        :model="statusForm"
        :rules="statusRules"
        label-width="80px"
      >
        <el-form-item label="审核状态" prop="status">
          <el-select
            v-model="statusForm.status"
            placeholder="审核状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusOptions.slice(1)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statusCancel">取 消</el-button>
        <el-button type="primary" @click="statusSubmitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  getAccessCodeDetail,
  postAccessCode,
  putAccessCode,
  delAccessCode,
  getUserAccessAreaCamera,
} from "@/api/accessCode";
import { listUser } from "@/api/system/user";

export default {
  name: "AccessCode",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      // 表格数据
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      total:0,
      // 审核状态
      statusOptions: [
        { value: "0", label: "待审核" },
        { value: "1", label: "审核通过" },
        { value: "2", label: "审核拒绝" },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accessUserName: undefined,
        status: undefined,
      },
      total: 0,
      // 创建时间范围
      dateRange: [],
      // 表单参数
      form: {
        accessUserName: undefined,
        accessCode: undefined,
        accessInterval: undefined,
        accessCount: undefined,
        validTime: [],
        submitUserId: undefined,
        submitUserName: undefined,
        intervalType: "0",
        newAccessInterval: undefined,
        deviceId: [[47,49],[47,48]],
      },
      // 表单校验
      rules: {
        accessUserName: [
          { required: true, message: "访问人不能为空", trigger: "blur" },
        ],
        accessCode: [
          { required: true, message: "访问码不能为空", trigger: "blur" },
          { validator: this.validateAccessCode, trigger: "blur" },
        ],
        accessInterval: [
          { required: true, message: "访问时长不能为空", trigger: "change" },
        ],
        accessCount: [
          { required: true, message: "访问次数不能为空", trigger: "blur" },
        ],
        validTime: [
          { required: true, message: "有效时间不能为空", trigger: "change" },
        ],
        submitUserId: [
          {
            required: true,
            message: "申请人不能为空",
            trigger: ["change", "blur"],
          },
        ],
        deviceId: [
          { required: true, message: "访问场景不能为空", trigger: "change" },
        ],
      },
      // 访问时长
      accessIntervalOptions: [
        {
          label: "10",
          value: 600,
        },
        {
          label: "30",
          value: 1800,
        },
        {
          label: "60",
          value: 3600,
        },
        {
          label: "120",
          value: 7200,
        },
        {
          label: "永久",
          value: -1,
        },
      ],
      // 申请人
      submitUserIdOptions: [],
      // 是否是管理员
      isAdmin: false,
      // 审核表单
      statusOpen: false,
      statusForm: {
        status: undefined,
      },
      statusRules: {
        status: [
          { required: true, message: "审核状态不能为空", trigger: "change" },
        ],
      },
      // 审核状态所需选中项ID
      statusBaseId: undefined,
      // 申请人下拉加载更多
      hasMore: true,
      pageSize: 20,
      currentPage: 1,
      submitUserTotal: 0,
      // 是否是自定义访问码
      isCustom: false,
      // 访问场景列表
      cameraTreeList: [],
      // 禁用当日之前时间
      pickerOptions: {
        disabledDate: (date) => {
          return date.getTime() < new Date().getTime() - 86400000;
        },
      },
    };
  },
  created() {
    this.getTableList();
    this.getIsAdmin();
    this.getCameraTree();
    if(process.env.NODE_ENV === 'development') {
      this.form.deviceId = [[1,36],[1,15]];
    }
  },

  methods: {
    // 是否是管理员
    getIsAdmin() {
      if (this.$store.state.user.id === 1) {
        this.isAdmin = true;
        this.submitUserIdOptions = [];
        this.currentPage = 1;
        this.getListUser();
      } else {
        this.form.submitUserId = this.$store.state.user.id;
        this.form.submitUserName = this.$store.state.user.nickName;
      }
    },
    /** 查询列表 */
    getTableList() {
      this.loading = true;
      getList(
        this.addDateRange({
          ...this.queryParams,
          filterBeginDate: this.dateRange[0],
          filterEndDate: this.dateRange[1],
        })
      ).then((response) => {
        this.tableList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表格根据value获取label
    getValue(options, value) {
      return options.find((item) => item.value === value)?.label;
    },
    // 管理员申请人列表
    getListUser(query) {
      const params = query
        ? {
            userName: query,
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          }
        : {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          };
      listUser(params).then((response) => {
        this.submitUserIdOptions = [
          ...this.submitUserIdOptions,
          ...response.rows,
        ];
        this.submitUserTotal = response.total;
        this.hasMore = this.submitUserIdOptions.length < this.submitUserTotal;
      });
    },
    // 访问场景列表
    getCameraTree() {
      const username = this.$store.state.user.name;
      getUserAccessAreaCamera({username}).then(res=>{
        this.cameraTreeList = this.removeEmptyChildren(res.data)
      })
    },
    removeEmptyChildren(arr) {
      return arr.map((item) => {
        // 如果当前对象有 children 属性且是空数组，删除该属性
        if (
          item.children &&
          Array.isArray(item.children) &&
          item.children.length === 0
        ) {
          delete item.children;
        }

        // 如果对象的 children 非空，递归处理每个子元素
        if (
          item.children &&
          Array.isArray(item.children) &&
          item.children.length > 0
        ) {
          item.children = this.removeEmptyChildren(item.children);
        }

        return item;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        accessUserName: undefined,
        accessCode: undefined,
        accessInterval: undefined,
        accessCount: undefined,
        deviceId: [[47,49],[47,48]],
        validTime: undefined,
        submitUserId: undefined,
        intervalType: "0",
        newAccessInterval: undefined,
      };
      if(process.env.NODE_ENV === 'development') {
        this.form.deviceId = [[1,36],[1,15]];
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getTableList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getIsAdmin();
      this.open = true;
      this.title = "新增访问码";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getIsAdmin();
      getAccessCodeDetail({ baseId: row.baseId }).then((response) => {
        this.form = response.data;
        if (this.form.intervalType == 0) {
          this.form.accessInterval = response.data.accessInterval / 60;
        }
        this.form.deviceId = JSON.parse(response.data.areaSelected);
        this.form.validTime = [response.data.beginDate, response.data.endDate];
        this.open = true;
        this.title = "修改访问码";
      });
    },
    // 审核
    handleApprove(row) {
      this.statusBaseId = row.baseId;
      this.resetForm("statusForm");
      this.statusOpen = true;
    },
    // 申请人搜索
    remoteMethod(query) {
      this.currentPage = 1;
      this.submitUserIdOptions = [];
      this.getListUser(query);
    },
    // 加载更多
    loadMore() {
      this.currentPage++;
      this.getListUser();
    },
    // 申请人信息
    handleChange(value) {
      this.form.submitUserName = this.submitUserIdOptions.find(
        (item) => item.userId === value
      ).nickName;
    },
    handleFocus() {
      this.currentPage = 1;
      this.submitUserIdOptions = [];
      this.$nextTick(() => {
        this.getListUser("");
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const arr = [];
          this.form.deviceId.forEach((item) => {
            arr.push(...item);
          });
          const newArr = Array.from(new Set(arr));
          const params = {
            ...this.form,
            deviceId: newArr.join(","),
            areaSelected: JSON.stringify(this.form.deviceId),
            beginDate: this.form.validTime[0],
            endDate: this.form.validTime[1],
            accessInterval:
              this.form.intervalType == 0
                ? this.form.newAccessInterval
                : this.form.accessInterval,
          };
          if(params.status) {
            delete params.status;
          }
          if (this.form.baseId != undefined) {
            putAccessCode(params).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getTableList();
            });
          } else {
            postAccessCode(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getTableList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const baseId = row.baseId;
      this.$modal
        .confirm("是否确认删除该数据项？")
        .then(function () {
          return delAccessCode(baseId);
        })
        .then(() => {
          this.getTableList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 随机生成访问码
    generateCode() {
      this.isCustom = false;
      this.form.accessCode = this.generateRandomString();
      this.$refs.form.validateField("accessCode");
    },
    generateRandomString() {
      // 定义可能的字符（数字和字母）
      const chars =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      let result = "";
      // 生成1到11之间的随机长度
      /*
       * 原先为1-11位
       * 后更改为6固定6位
       * */
      // const length = Math.floor(Math.random() * 11) + 1;
      const length = 6;

      for (let i = 0; i < length; i++) {
        // 随机选择一个字符
        const randomIndex = Math.floor(Math.random() * chars.length);
        result += chars[randomIndex];
      }
      return result;
    },
    // 审核确认
    statusSubmitForm() {
      this.$refs["statusForm"].validate((valid) => {
        if (valid) {
          putAccessCode({
            ...this.statusForm,
            baseId: this.statusBaseId,
          }).then((response) => {
            this.$modal.msgSuccess("审核成功");
            this.statusOpen = false;
            this.getTableList();
          });
        }
      });
    },
    // 审核取消
    statusCancel() {
      this.statusOpen = false;
    },
    // 访问码校验
    validateAccessCode(rule, value, callback) {
      if (this.isCustom) {
        const mobileReg = /^1[3-9]\d{9}$/;
        if (!mobileReg.test(value)) {
          callback(new Error("请输入正确的11位手机号码"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 访问码
    handleCodeChange() {
      this.isCustom = true;
    },
    // 是否选择自定义访问时长
    intervalTypeChange() {
      this.form.accessInterval = "";
    },
    // 自定义访问时长
    handleAccessIntervalInput(value) {
      this.form.accessInterval = value.replace(/[^0-9]/g, '');
      if(this.form.accessInterval) {
        this.form.newAccessInterval = Number(this.form.accessInterval) * 60;
      }
    },
    handleIntervalChange(value) {
      this.form.newAccessInterval = Number(value) * 60;
    },
    // 访问次数处理
    handleAccessCountInput(value) {
      this.form.accessCount = value.replace(/[^0-9]/g, '');
    },
  },
};
</script>

<style lang="scss" scoped>
.input-group {
  display: flex;
  align-items: center;

  .el-input,
  .el-select {
    flex: 1;
    margin-right: 5px;
  }

  span {
    cursor: pointer;
  }
}

.load-more {
  padding: 8px 0;
  font-size: 12px;
  text-align: center;
  color: #409eff;
  cursor: pointer;
}

.load-more:hover {
  background-color: #f5f7fa;
}

::v-deep {
  .el-date-picker__time-header .el-time-panel__content::after {
    display: none;
  }

  .el-time-spinner__wrapper .el-scrollbar:nth-child(3) {
    display: none;
  }
}
</style>
